/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Tela.java
 *
 * Created on 18/06/2010, 13:40:12
 */
package GUI;

import com.sun.media.jai.widget.DisplayJAI;
import java.awt.Point;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
import pa_jai.Recorte;

/**
 *
 * @author petiano
 */
public class Tela extends javax.swing.JFrame {

    /** Creates new form Tela */
    public Tela() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        imagePane = new javax.swing.JScrollPane();
        abrir = new javax.swing.JButton();
        histograma = new javax.swing.JButton();
        binarizacao = new javax.swing.JButton();
        recorte = new javax.swing.JButton();
        desfaz = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        imagePane.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                imagePaneMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                imagePaneMouseReleased(evt);
            }
        });
        imagePane.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                imagePaneMouseDragged(evt);
            }
        });

        abrir.setText("Abrir");
        abrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirActionPerformed(evt);
            }
        });

        histograma.setText("Gerar histograma");
        histograma.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                histogramaActionPerformed(evt);
            }
        });

        binarizacao.setText("Binarização");
        binarizacao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                binarizacaoActionPerformed(evt);
            }
        });

        recorte.setText("Recortar");
        recorte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                recorteActionPerformed(evt);
            }
        });

        desfaz.setText("Desfazer");
        desfaz.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                desfazActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(desfaz, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
                    .addComponent(recorte, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
                    .addComponent(binarizacao, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
                    .addComponent(histograma, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
                    .addComponent(abrir, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(imagePane, javax.swing.GroupLayout.DEFAULT_SIZE, 655, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(abrir)
                        .addGap(18, 18, 18)
                        .addComponent(histograma)
                        .addGap(18, 18, 18)
                        .addComponent(binarizacao)
                        .addGap(18, 18, 18)
                        .addComponent(recorte)
                        .addGap(18, 18, 18)
                        .addComponent(desfaz))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(imagePane, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void abrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abrirActionPerformed
        // TODO add your handling code here:

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Abrir Imagem");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Imagens TIFF", "tif", "tiff"));

        int result = fileChooser.showOpenDialog(null);

        if (result == JFileChooser.APPROVE_OPTION) {
            File choosedFile = fileChooser.getSelectedFile();
            if (choosedFile != null) {
                imagemAtual = choosedFile.getAbsolutePath();
                this.abrirImagem();
            }
        }
    }//GEN-LAST:event_abrirActionPerformed

    private void histogramaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_histogramaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_histogramaActionPerformed

    private void binarizacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_binarizacaoActionPerformed
        // TODO add your handling code here:
        imagemAuxiliar = imagemOriginal;
        ParameterBlock pb = new ParameterBlock();
        pb.addSource(imagemAuxiliar);
        pb.add(127.0);
        imagemOriginal = JAI.create("binarize", pb);
        this.mostrarImagem(imagemOriginal);
    }//GEN-LAST:event_binarizacaoActionPerformed

    private void recorteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recorteActionPerformed
        // TODO add your handling code here:     
        r = new Recorte();
        JOptionPane.showMessageDialog(null, "Selecione a região de recorte da imagem...");
    }//GEN-LAST:event_recorteActionPerformed

    private void imagePaneMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imagePaneMouseDragged
        // TODO add your handling code here:
    }//GEN-LAST:event_imagePaneMouseDragged

    private void imagePaneMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imagePaneMousePressed
        // TODO add your handling code here:

        // Relaciona a coordenada capturada pelo mouse, com a coordenada da imagem;
        if(r != null)
        {
            r.setX0((float) evt.getX()-display.getLocation().x);
            r.setY0((float) evt.getY()-display.getLocation().y);
        }
    }//GEN-LAST:event_imagePaneMousePressed

    private void imagePaneMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imagePaneMouseReleased
        // TODO add your handling code here:
        if(r != null)
        {
            r.setX1((float) evt.getX()-display.getLocation().x);
            r.setY1((float) evt.getY()-display.getLocation().y);
            r.calculaDimensoes();

            // Recorta a imagem;
            imagemOriginal = r.crop(imagemAuxiliar);
            mostrarImagem(imagemOriginal);
        }
    }//GEN-LAST:event_imagePaneMouseReleased

    private void desfazActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_desfazActionPerformed
        // TODO add your handling code here:
        this.abrirImagem();
    }//GEN-LAST:event_desfazActionPerformed

    public void mostrarImagem(PlanarImage imagem) {

        display = new DisplayJAI(imagem);
        JPanel panel = new JPanel();
        panel.setSize(imagem.getWidth(), imagem.getHeight());
        panel.add(display);

        int x = (imagePane.getWidth() - panel.getWidth()) / 2;
        int y = (imagePane.getHeight() - panel.getHeight()) / 2;

        panel.setLocation(x, y);
        imagePane.setViewportView(panel);
        imagePane.getViewport().setViewPosition(new Point(0, 0));
        imagePane.repaint();
        imagePane.updateUI();
    }

    public void abrirImagem() {

        try {
            imagemOriginal = JAI.create("fileload", imagemAtual);
            imagemAuxiliar = imagemOriginal;
            mostrarImagem(imagemOriginal);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Tela().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton abrir;
    private javax.swing.JButton binarizacao;
    private javax.swing.JButton desfaz;
    private javax.swing.JButton histograma;
    private javax.swing.JScrollPane imagePane;
    private javax.swing.JButton recorte;
    // End of variables declaration//GEN-END:variables
    private PlanarImage imagemOriginal, imagemAuxiliar;
    private Recorte r;
    private String imagemAtual = "";
    DisplayJAI display;
}
